package com.mti.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.component.UserTypeInfo;
import com.mti.component.redis.RedisUtil;
import com.mti.component.snowflake.KeyWorker;
import com.mti.configuration.SystemConfig;
import com.mti.dao.dto.LfZdryDto;
import com.mti.dao.dto.OrganizationDto;
import com.mti.dao.dto.ZdryDto;
import com.mti.dao.kmmodel.KmArmingTaskEntity;
import com.mti.dao.model.*;
import com.mti.dao.qo.AddressQO;
import com.mti.dao.qo.LfZdryQO;
import com.mti.enums.*;
import com.mti.exception.BusinessException;
import com.mti.jwt.AccountBo;
import com.mti.jwt.RequestUtils;
import com.mti.kafka.Producer;
import com.mti.kafka.entity.ZdryEntity;
import com.mti.mapper.KmZdryFollowMapper;
import com.mti.mapper.LfZdryBaseMapper;
import com.mti.mapper.LfZdryBaseTempMapper;
import com.mti.service.*;
import com.mti.utils.*;
import com.mti.vo.SpecialPersonStatisticsDataVO;
import com.mti.websocket.SocketType;
import com.mti.websocket.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * <p>
 * 重点人员表 服务实现类
 * </p>
 *
 * @author chenf
 * @since 2020-03-25
 */
@Slf4j
@Service
public class LfZdryBaseServiceImpl extends ServiceImpl<LfZdryBaseMapper, LfZdryBaseEntity> implements LfZdryBaseService {
    @Value("${zdry.txUrl}")
    private String zdryTxUrl; // 注入配置属性

    @Value("${zdry.txFileAddr}")
    private String zdryTxFileAddr; // 注入配置属性

    @Value("${kafka.servers}")
    private String servers;

    @Value("${kafkaTxUrl}")
    private String kafkaTxUrl;

    @Autowired
    private ISpecialPersonService specialPersonService;

    @Autowired
    private ISysDictService service;

    @Autowired
    private LfZdryBaseWhiteService lfZdryBaseWhiteService;

    @Resource
    private LfZdryBaseMapper mapper;

    @Resource
    private LfZdryBaseTempMapper tempZdryMapper;

    @Resource
    private LfZdryBaseTempService lfZdryBaseTempService;

    @Autowired
    IContactCardPoliceForceService contactCardPoliceForceService;

    @Autowired
    IContactPoliceRoomService contactPoliceRoomService;

    @Autowired
    ILfZdryControlPcService lfZdryControlPcService;

    @Autowired
    ILfZdryControlPcReceiveService lfZdryControlPcReceiveService;

    @Autowired
    private ILfGkjlService gkjlService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SystemConfig systemConfig;

    @Autowired
    private RequestUtils requestUtils;

    @Resource
    private WebSocketUtils webSocketUtils;

    @Autowired
    private SpecialPersonComponent specialPersonComponent;

    @Autowired
    private ISysDictService iSysDictService;

    @Autowired
    private CacheableService cacheableService;
    @Autowired
    private ExecutorService executorService;


    @Autowired
    private LfZdryBaseTempService tempService;

    @Autowired
    private KmZdryTypeService kmZdryTypeService;

    @Autowired
    private KmZdryHomeService kmZdryHomeService;

    @Autowired
    private KmZdryCustomService kmZdryCustomService;

    @Autowired
    private KmZdryAssistService kmZdryAssistService;

    @Autowired
    private LfZdryHistoryLogService lfZdryHistoryLogService;

    @Autowired
    private KmZdryZrbmService kmZdryZrbmService;

    @Autowired
    private TTaskFileService taskFileService;

    @Autowired
    private ILfZtryyjsjService lfZtryyjsjService;

    @Autowired
    private ILfZdryApproveLogService approveLogService;

    @Autowired
    private GetRemoteIpUtil getRemoteIpUtil;
    @Autowired
    private KmZdryFollowMapper followMapper;

    @Autowired
    private IKmArmingTaskService taskService;

    @Autowired
    private TPfGroupZdryService tPfGroupZdryService;


    @Override
    public List<LfZdryBaseEntity> findExportExeclData(LfZdryQO qo) {
        return this.getBaseMapper().findExportExeclData(qo);
    }

    @Override
    public List<LfZdryBaseEntity> findExportExeclDataNumber(List<String> listNumber) {
        return this.getBaseMapper().findExportExeclDataNumber(listNumber);
    }


    @Override
    @Transactional
    public boolean saveZdry(ServerWebExchange exchange, LfZdryBaseEntity entity) {
        long startTime = new Date().getTime();
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        Integer existCount = this.count(new QueryWrapper<LfZdryBaseEntity>().eq("sfzh", entity.getSfzh())) + tempService.count(new QueryWrapper<LfZdryBaseTempEntity>().eq("sfzh", entity.getSfzh()));
        if (existCount > 0 && entity.getResubmitFlag() == 0)
            throw new BusinessException(500, "你添加的重点人员：" + entity.getXm() + "在系统中已经存在！");
        entity.setLastOperate("save");
        boolean resubmitFlag = false;
        if (0 == entity.getResubmitFlag()) {
            entity.setId(String.valueOf(KeyWorker.nextId()));
        } else {
            resubmitFlag = true;//重新提交标志；
        }
        Map<String, String> zrpcses = cacheableService.getZrpcs("3");
        entity.setSspcs(zrpcses.get(entity.getSspcsId())); //设置责任派出所
        // 获取性别
        entity.setXb(IdCardUtils.getGenderByIdCard(entity.getSfzh()));
        //流程相关的逻辑
        entity.setSubmitter(bo.getId());
        String role = bo.getRoleList().get(0).getId();
        entity.setSubmitterRoleId(role);
        //OWNER_ORG_DATA
        if (role.equals(RoleType.POLICE_STATION_DATA.getType())) { //派出所用户 4
            entity.setProcessType(1);
            entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());

        } else if (role.equals(RoleType.BREACH_REVIEW_DATA.getType()) || role.equals(RoleType.BREACH_DATA.getType())) { // 分局用户 3 6
            entity.setProcessType(12);
            entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
        } else if (role.equals(RoleType.OWNER_REVIEW_DATA.getType()) || role.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType()) || role.equals(RoleType.OWNER_ORG_DATA.getType())) {   //警种和情报中心用户1 2 5
            entity.setProcessType(0);
            entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
        }
        //判断管控民警是否被分配
        if (entity.getGkmj() != null && !"".equals(entity.getGkmj())) {
            entity.setReceiveFlag(ReceiveFlag.RECEIVED.getStatus());
        } else {
            entity.setReceiveFlag(ReceiveFlag.NOT_RECEIVED.getStatus());
        }
        boolean flag = false;
        entity.setCreateTimex(new Date());
        entity.setUpdateTimex(new Date());
        //人员类型表保存  id 不为空，则为驳回重新提交新增
        for (KmZdryTypeEntity kmZdryTypeEntity : entity.getTypeList()) {
            if (null != kmZdryTypeEntity.getZzjz() && 1 == kmZdryTypeEntity.getZzjz()) {
                entity.setZrbm(kmZdryTypeEntity.getZrbm());
            }
            if (null == kmZdryTypeEntity.getId()) {
                kmZdryTypeEntity.setId(String.valueOf(KeyWorker.nextId()));
                kmZdryTypeEntity.setZdryId(entity.getId());
                kmZdryTypeService.save(kmZdryTypeEntity);
            } else {
                if (kmZdryTypeEntity.getRylb() != null && kmZdryTypeEntity.getXl() != null) {
                    kmZdryTypeService.updateById(kmZdryTypeEntity);
                } else {
                    kmZdryTypeService.removeById(kmZdryTypeEntity.getId());
                }
            }
        }
        if (entity.getZrbm() == null) {
            entity.setZrbm(entity.getTypeList().get(0).getZrbm());
        }
        //辅助信息新增
        for (KmZdryAssistEntity kmZdryAssistEntity : entity.getAssistList()) {

            if (StringUtils.isNotEmpty(kmZdryAssistEntity.getInfoValue())) {
                if (null == kmZdryAssistEntity.getId()) {
                    kmZdryAssistEntity.setId(String.valueOf(KeyWorker.nextId()));
                    kmZdryAssistEntity.setZdryId(entity.getId());
                    kmZdryAssistService.save(kmZdryAssistEntity);
                } else {
                    kmZdryAssistService.updateById(kmZdryAssistEntity);
                }
                //辅助信息值为空，则删除该辅助信息
            } else {
                if (StringUtils.isNotEmpty(kmZdryAssistEntity.getId())) {
                    kmZdryAssistService.removeById(kmZdryAssistEntity.getId());
                }
            }
        }
        int index = 0;
        for (KmZdryHomeEntity kmZdryHomeEntity : entity.getJzdList()) {
            if (index == 0) {
                kmZdryHomeEntity.setZjzdbj(1);
            }
            if (null == kmZdryHomeEntity.getId()) {
                kmZdryHomeEntity.setId(String.valueOf(KeyWorker.nextId()));
                kmZdryHomeEntity.setZdryId(entity.getId());
                kmZdryHomeService.save(kmZdryHomeEntity);
            } else {
                kmZdryHomeService.updateById(kmZdryHomeEntity);
            }
            index++;
        }
        //默认以第一条为主
        entity.setXzzs(entity.getJzdList().get(0).getXzzs());
        entity.setXzzss(entity.getJzdList().get(0).getXzzss());
        entity.setXzzx(entity.getJzdList().get(0).getXzzx());
        entity.setXzz(entity.getJzdList().get(0).getXzz());
        entity.setX(entity.getJzdList().get(0).getX());
        entity.setY(entity.getJzdList().get(0).getY());

        for (KmZdryCustomEntity kmZdryCustomEntity : entity.getCustomList()) {
            if (null == kmZdryCustomEntity.getId()) {
                kmZdryCustomEntity.setId(String.valueOf(KeyWorker.nextId()));
                kmZdryCustomEntity.setZdryId(entity.getId());
                kmZdryCustomService.save(kmZdryCustomEntity);
            } else {
                kmZdryCustomService.updateById(kmZdryCustomEntity);
            }
        }
        for (TTaskFileEntity fileEntity : entity.getFileList()) {
            if (null == fileEntity.getId()) {
                fileEntity.setId(String.valueOf(KeyWorker.nextId()));
                fileEntity.setBussType("7");//7 重点人员新增
                fileEntity.setBussId(entity.getId());
                taskFileService.save(fileEntity);
            } else {
                taskFileService.updateById(fileEntity);
            }
        }
        entity.setSfzp("1");
        if (ApproveStatus.COMPLETED.getStatus().equals(entity.getApproveStatus())) {
            flag = this.save(entity);
            // 推送重点人员信息
            this.sendKeyPersonMessage(entity.getId(), "0");

        } else {
            LfZdryBaseTempEntity zdry = new LfZdryBaseTempEntity();
            BeanUtils.copyProperties(entity, zdry);
            //重新提交新增逻辑
            if (resubmitFlag) {
                flag = tempService.updateById(zdry);
            } else {
                flag = tempService.save(zdry);
            }
            /**
             * 如果是待处理类型，则对接收移交的分局和派出所发送消息
             * 保存成功后发送消息给对应的用户
             */
            if (flag) {
                this.sendMessage(entity, "stayHandle");
            }
        }

        // 审批日志表
        flag = this.operatLog("新增", bo, entity, "新增重点人员", entity.getApprovalOpinion(), exchange);
        long endTime = new Date().getTime();
        log.info("执行修改花费：" + (endTime - startTime) / 1000);
        return flag;
    }


    @Override
    public IPage<LfZdryBaseEntity> queryPageList(LfZdryQO qo, ServerWebExchange exchange) {
        Page<LfZdryEntity> page = new Page<>(qo.getStart(), qo.getSize());
        qo.setRylbxList(ListUtils.removeNullElement(qo.getRylbxList()));
        qo.setSfzkList(ListUtils.removeNullElement(qo.getSfzkList()));
        qo.setZrbmList(ListUtils.removeNullElement(qo.getZrbmList()));
        qo.setSsxqList(ListUtils.removeNullElement(qo.getSsxqList()));
        qo.setSsxqIdList(ListUtils.removeNullElement(qo.getSsxqIdList()));
        qo.setGkjbxList(ListUtils.removeNullElement(qo.getGkjbxList()));
        qo.setMjidList(ListUtils.removeNullElement(qo.getMjidList()));
        qo.setSspcsList(ListUtils.removeNullElement(qo.getSspcsList()));
        qo.setRylyList(ListUtils.removeNullElement(qo.getRylyList()));
        qo.setRysxList(ListUtils.removeNullElement(qo.getRysxList()));

        // qo.setApproveStatus(ApproveStatus.COMPLETED.getStatus().toString());

        // 权限相关代码
        this.setUpAuthority(exchange, qo);
        //根据布控任务查询布控人员
        if(null != qo.getBkrwId() && !"".equals(qo.getBkrwId())){

            List<TPfGroupZdryEntity> list = tPfGroupZdryService.list(new QueryWrapper<TPfGroupZdryEntity>().eq("group_id",qo.getBkrwId()));
            if(null != list && list.size() > 0){
                List<String> sfzhList = new ArrayList<>();
                for(TPfGroupZdryEntity tPfGroupZdryEntity: list){
                    sfzhList.add(tPfGroupZdryEntity.getZdryId());
                }
                qo.setSfzhList(sfzhList);
            }else {
               return new Page<>(qo.getStart(), qo.getSize());
            }
        }

        return mapper.queryPage(page, qo);
    }

    @Override
    public LfZdryBaseEntity getBySfzh(String sfzh, String currentUserId) {
        LfZdryBaseEntity baseEntity = this.getOne(new QueryWrapper<LfZdryBaseEntity>().eq("sfzh", sfzh).lambda().last("LIMIT 1"));
        if (null == baseEntity) {
            LfZdryBaseWhiteEntity whiteEntity = lfZdryBaseWhiteService.getOne(new QueryWrapper<LfZdryBaseWhiteEntity>().eq("sfzh", sfzh).lambda().last("LIMIT 1"));
            if (null != whiteEntity) {
                baseEntity = new LfZdryBaseEntity();
                baseEntity.setIsDelete(1);
                BeanUtils.copyProperties(whiteEntity, baseEntity);
            } else {
                baseEntity = new LfZdryBaseEntity();
                return baseEntity;
            }
        }
        List<KmZdryCustomEntity> customList = kmZdryCustomService.list(new QueryWrapper<KmZdryCustomEntity>().eq("zdry_id", baseEntity.getId()));
        baseEntity.setCustomList(customList);
        List<KmZdryTypeEntity> typeList = kmZdryTypeService.list(new QueryWrapper<KmZdryTypeEntity>().eq("zdry_id", baseEntity.getId()));
        baseEntity.setTypeList(typeList);
        List<KmZdryAssistEntity> assistList = kmZdryAssistService.list(new QueryWrapper<KmZdryAssistEntity>().eq("zdry_id", baseEntity.getId()));
        baseEntity.setAssistList(assistList);
        List<KmZdryHomeEntity> homeList = kmZdryHomeService.list(new QueryWrapper<KmZdryHomeEntity>().eq("zdry_id", baseEntity.getId()));
        baseEntity.setJzdList(homeList);
        List<TTaskFileEntity> fileList = new ArrayList<>();
        fileList = taskFileService.list(new QueryWrapper<TTaskFileEntity>().eq("buss_id", baseEntity.getId()));
        baseEntity.setFileList(fileList);
        baseEntity.setIsFollow(0);
        if (!org.springframework.util.StringUtils.isEmpty(currentUserId)) {
            baseEntity.setIsFollow(followMapper.isFollow(baseEntity.getId(), currentUserId));
        }
        //List<ZdryYjUtilBean> gjList = lfZtryyjsjService.getZdryAllYj(sfzh);
        //baseEntity.setGjList(gjList) ;
        return baseEntity;
    }

    @Override
    public LfZdryBaseTempEntity getDetailBySfzh(String sfzh) {
        LfZdryBaseTempEntity baseEntity = tempService.getOne(new QueryWrapper<LfZdryBaseTempEntity>().eq("sfzh", sfzh).lambda().last("LIMIT 1"));
        List<KmZdryCustomEntity> customList = kmZdryCustomService.list(new QueryWrapper<KmZdryCustomEntity>().eq("zdry_id", baseEntity.getId()));
        baseEntity.setCustomList(customList);
        List<KmZdryTypeEntity> typeList = kmZdryTypeService.list(new QueryWrapper<KmZdryTypeEntity>().eq("zdry_id", baseEntity.getId()));
        baseEntity.setTypeList(typeList);
        List<KmZdryAssistEntity> assistList = kmZdryAssistService.list(new QueryWrapper<KmZdryAssistEntity>().eq("zdry_id", baseEntity.getId()));
        baseEntity.setAssistList(assistList);
        List<KmZdryHomeEntity> homeList = kmZdryHomeService.list(new QueryWrapper<KmZdryHomeEntity>().eq("zdry_id", baseEntity.getId()));
        baseEntity.setJzdList(homeList);
        List<TTaskFileEntity> fileList = new ArrayList<>();
        fileList = taskFileService.list(new QueryWrapper<TTaskFileEntity>().eq("buss_id", baseEntity.getId()));
        baseEntity.setFileList(fileList);
        //List<ZdryYjUtilBean> gjList = lfZtryyjsjService.getZdryAllYj(sfzh);
        //baseEntity.setGjList(gjList) ;
        return baseEntity;

    }


    @Override
    @Transactional
    public Integer deleteZdry(String id, ServerWebExchange exchange) {
        //删除关联数据
        /*
         * kmZdryTypeService.removeById(id); kmZdryTypeService.removeById(id);
         * kmZdryAssistService.removeById(id); kmZdryHomeService.removeById(id);
         * kmZdryCustomService.removeById(id); taskFileService.removeById(id);
         */
        // 推送重点人员信息
        this.sendKeyPersonMessage(id, "2");

        LfZdryBaseEntity entity = mapper.selectById(id);
        LfZdryBaseWhiteEntity LfZdryBaseWhiteEntity = new LfZdryBaseWhiteEntity();
        BeanUtils.copyProperties(entity, LfZdryBaseWhiteEntity);
        LfZdryBaseWhiteEntity.setDeleteTime(new Date());
        lfZdryBaseWhiteService.save(LfZdryBaseWhiteEntity);
        this.operatLog(id, exchange, entity);
        //删除重点人员
        return mapper.deleteById(id);
    }

    @Override
    public List<ZdryDto> queryZdryByCondition(LfZdryDto lfZdryDto) {
        List<ZdryDto> lfZdryBaseEntities = this.getBaseMapper().queryZdryByCondition(lfZdryDto);
        return lfZdryBaseEntities;
    }

    @Override
    @Transactional
    public boolean updateZdry(ServerWebExchange exchange, LfZdryBaseEntity entity) {
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        entity.setLastOperate("update");
        //基本信息 ：风险等级、人员属性、预警处置类别、稳控状态
//        String[] controlInfos = {"rysx", "gkjb", "yjczlb", "wkzt"};//"xm",20200421
        String[] controlInfos = {"rysx", "gkjb", "yjczlb"};//"xm",20201120
        //String[] baseInfos={"xm","sfzh","ssxq","sspcs","hjs","hjss","hjx","hjd","rysx","gkjb","yjczlb"};
        //辅助信息
        //String[] assistInfos={"sjh","wx","qq","mxcph","sjsyclhp","gkmj","mjlxdh","hjs","hjsS","hjx","hjd","bz"};
        //管控信息
        //String[] policeInfos={"rylbx","xl"};
        /*Map<String,String> zrpcses = cacheableService.getZrpcs("3");
        entity.setSspcs(zrpcses.get(entity.getSspcs())); //设置责任派出所
        */
        // 获取性别
        entity.setXb(IdCardUtils.getGenderByIdCard(entity.getSfzh()));
        //流程相关的逻辑
        entity.setSubmitter(bo.getId());
        String role = bo.getRoleList().get(0).getId();
        entity.setSubmitterRoleId(role);
        boolean flag = false;
        entity.setUpdateTimex(new Date());
        entity.setSfzp("1");
        //默认的修改类型为辅助信息；
        int updateType = UpdateType.ASSIST_INFO.getCode();
        LfZdryBaseEntity resourceEntity = this.getById(entity.getId());
        List<String> modifyList = specialPersonComponent.getModifyList(entity, resourceEntity);
        String logRecord = specialPersonComponent.getModifyInfo(entity, resourceEntity);
        //空字符替换
        if (logRecord.contains("【】")) {
            logRecord = logRecord.replaceAll("【】", "【空】");
        }
        //修改的字段是包含基本信息，包含则直接跳出
//        if(updateType==UpdateType.BASE_INFO.getCode()) {
        for (String controlInfo : controlInfos) {
            if (modifyList.contains(controlInfo)) {
                updateType = UpdateType.CONTROL_INFO.getCode();
                break;
            }
        }
//        }
//    	LfZdryTempEntity tempZdry = new LfZdryTempEntity();
//    	BeanUtils.copyProperties(entity, tempZdry);
        /**
         *   辅助信息修改 、基本信息修改 、管控信息修改
         *   1:ASSIST_INFO/ 2:baseInfo/ 3:CONTROL_INFO/
         * 	【2:派出所管控信息修改】------->审核分局---->警种审核---->审核完毕
         *  【21：派出所非管控信息（基本+辅助）修改 ,分局非管控信息（基本+辅助）修改，警种用户信息修改，情报中心修改】
         *	【25：分局管控信息修改 ------>警种审核---->审核完毕】
         */
        if (role.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所用户
            if (updateType == UpdateType.CONTROL_INFO.getCode()) {
                entity.setProcessType(2);
                entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
            } else {
                entity.setProcessType(21);
                entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
            }
        } else if (role.equals(RoleType.BREACH_REVIEW_DATA.getType())) { //分局用户
            if (updateType == UpdateType.CONTROL_INFO.getCode()) {
                entity.setProcessType(25);//分局变更管控信息
                entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
            } else {
                entity.setProcessType(21);
                entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
            }
        } else if (role.equals(RoleType.OWNER_REVIEW_DATA.getType()) ||
                role.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 警种用户|| 情报中心
            entity.setProcessType(21);
            entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
        }

        //人员类型表保存
        for (KmZdryTypeEntity kmZdryTypeEntity : entity.getTypeList()) {
            if (null == kmZdryTypeEntity.getZzjz()) {
                kmZdryTypeService.removeById(kmZdryTypeEntity.getId());
            } else {
                if (1 == kmZdryTypeEntity.getZzjz()) {
                    entity.setZrbm(kmZdryTypeEntity.getZrbm());
                }
            }
            if (null == kmZdryTypeEntity.getId()) {
                kmZdryTypeEntity.setId(String.valueOf(KeyWorker.nextId()));
                kmZdryTypeEntity.setZdryId(entity.getId());
                kmZdryTypeService.save(kmZdryTypeEntity);
            } else {
                if (kmZdryTypeEntity.getZzjz() != null) {
                    kmZdryTypeService.updateById(kmZdryTypeEntity);
                }
            }
        }
        if (entity.getZrbm() == null) {
            entity.setZrbm(entity.getTypeList().get(0).getZrbm());
        }
        //辅助信息新增
        for (KmZdryAssistEntity kmZdryAssistEntity : entity.getAssistList()) {

            if (StringUtils.isNotEmpty(kmZdryAssistEntity.getInfoValue())) {
                if (null == kmZdryAssistEntity.getId()) {
                    kmZdryAssistEntity.setId(String.valueOf(KeyWorker.nextId()));
                    kmZdryAssistEntity.setZdryId(entity.getId());
                    kmZdryAssistService.save(kmZdryAssistEntity);
                } else {
                    kmZdryAssistService.updateById(kmZdryAssistEntity);
                }
                //辅助信息值为空，则删除该辅助信息
            } else {
                if (StringUtils.isNotEmpty(kmZdryAssistEntity.getId())) {
                    kmZdryAssistService.removeById(kmZdryAssistEntity.getId());
                }
            }
        }
        int index = 0;
        for (KmZdryHomeEntity kmZdryHomeEntity : entity.getJzdList()) {
            if (index == 0) {
                kmZdryHomeEntity.setZjzdbj(1);
            }
            if (null == kmZdryHomeEntity.getId()) {
                kmZdryHomeEntity.setId(String.valueOf(KeyWorker.nextId()));
                kmZdryHomeEntity.setZdryId(entity.getId());
                kmZdryHomeService.save(kmZdryHomeEntity);
            } else {
                if (StringUtils.isNotEmpty(kmZdryHomeEntity.getZdryId())) {
                    kmZdryHomeService.updateById(kmZdryHomeEntity);
                } else {
                    kmZdryHomeService.removeById(kmZdryHomeEntity.getId());
                }
            }
            index++;
        }
        if (entity.getJzdList() != null && entity.getJzdList().size() > 0) {
            //kmZdryHomeService.updateById(entity.getJzdList().get(0));
            entity.setXzzs(entity.getJzdList().get(0).getXzzs());
            entity.setXzzss(entity.getJzdList().get(0).getXzzss());
            entity.setXzzx(entity.getJzdList().get(0).getXzzx());
            entity.setXzz(entity.getJzdList().get(0).getXzz());
            entity.setX(entity.getJzdList().get(0).getX());
            entity.setY(entity.getJzdList().get(0).getY());
        }

        for (KmZdryCustomEntity kmZdryCustomEntity : entity.getCustomList()) {
            if (null == kmZdryCustomEntity.getId()) {
                kmZdryCustomEntity.setId(String.valueOf(KeyWorker.nextId()));
                kmZdryCustomEntity.setZdryId(entity.getId());
                kmZdryCustomService.save(kmZdryCustomEntity);
            } else {
                if (StringUtils.isNotEmpty(kmZdryCustomEntity.getZdryId())) {
                    kmZdryCustomService.updateById(kmZdryCustomEntity);
                } else {
                    kmZdryCustomService.removeById(kmZdryCustomEntity.getId());
                }
            }
        }
        //taskFileService.removeByZdryId(entity.getId());
        for (TTaskFileEntity fileEntity : entity.getFileList()) {
            if (StringUtils.isNotEmpty(fileEntity.getFileUrl())) {
                if (StringUtils.isEmpty(fileEntity.getId())) {
                    fileEntity.setId(String.valueOf(KeyWorker.nextId()));
                    fileEntity.setBussType("7");//7 重点人员新增
                    fileEntity.setBussId(entity.getId().toString());
                    taskFileService.save(fileEntity);
                } else {
                    taskFileService.updateById(fileEntity);
                }
                //附件url为空，id不为空，则为删除数据
            } else {
                if (StringUtils.isNotEmpty(fileEntity.getId())) {
                    taskFileService.removeById(fileEntity.getId());
                }
            }
        }
        // 设置完入库
        if (ApproveStatus.COMPLETED.getStatus().equals(entity.getApproveStatus())) {
            //判断民警被赋值后，则对接收标记置成已接收的状态；
            if (StringUtils.isNotEmpty(entity.getGkmj())) {
                entity.setReceiveFlag(ReceiveFlag.RECEIVED.getStatus());
            }
            flag = this.updateById(entity);

            // 推送重点人员信息
            this.sendKeyPersonMessage(entity.getId(), "1");

        } else {
            LfZdryBaseTempEntity tempZdry = new LfZdryBaseTempEntity();
            BeanUtils.copyProperties(entity, tempZdry);
            if (1 == entity.getResubmitFlag()) {
                flag = tempService.updateById(tempZdry);
            } else {
                flag = tempService.save(tempZdry);
            }
            /**
             * 如果是待处理类型，则对接收移交的分局和派出所发送消息
             * 保存成功后发送消息给对应的用户
             */
            if (flag) {
                this.sendMessage(entity, "stayHandle");
            }
        }

        // 记录审批日志
        flag = this.operatLog("修改", bo, entity, logRecord, entity.getApprovalOpinion(), exchange);
        return flag;
    }

    /**
     * 操作日志方法
     *
     * @param type
     * @param bo
     * @param entity
     * @param logRecord
     * @return
     */
    @Override
    public boolean operatLog(String type, AccountBo bo, LfZdryBaseEntity entity, String logRecord, String opinion, ServerWebExchange exchange) {
        // 记录审批日志
        LfZdryApproveLogEntity logEntity = new LfZdryApproveLogEntity();
        logEntity.setCreator(bo.getPersonBo().getName());
        logEntity.setSpId(entity.getId());
        logEntity.setApproveResult(logRecord);
        logEntity.setOperation(type);
        logEntity.setOperateDept(bo.getOrganizationBo().getShortName());
        logEntity.setAddition(opinion);
        //每次新开始流程，则将该ID的重点人员之前log都标记成1 ，新开始log记录置成标记0 ；
        if (ApproveStatus.COMPLETED.getStatus().equals(entity.getApproveStatus())) {//||"reject".equals(entity.getReviewState())
            logEntity.setApprovingFlag("1");
            //更新最新一次的审核标志
            approveLogService.updateFlagByZdryId(entity.getId());
        } else {
            logEntity.setApprovingFlag("0");
        }
        specialPersonService.approveKMSpecialPerson(logEntity);
        //历史记录
        LfZdryHistoryLogEntity history = new LfZdryHistoryLogEntity();
        history.setCreator(bo.getPersonBo().getName());
        history.setCreatorCode(bo.getPersonBo().getPoliceCode());
        history.setCreateTime(new Date());
        history.setSpId(entity.getId());
        history.setApproveResult(logRecord);
        history.setOperation(type);
        history.setOperateDept(bo.getOrganizationBo().getShortName());
        history.setAddition(opinion);
        history.setFunctionModule("重点人员模块");

        ServerHttpRequest request = exchange.getRequest();
        String ip = getRemoteIpUtil.getRemoteIP(request);
        history.setOperateIp(ip);

        if (null != entity.getProcessType() && entity.getProcessType() == 3) {
            //移交类型
            history.setType(4);
        } else {
            //变更类型
            history.setType(3);
        }
        boolean flag = lfZdryHistoryLogService.save(history);

        return flag;
    }


    @Override
    @Transactional
    public boolean transfer(ServerWebExchange exchange, LfZdryBaseEntity entity) {
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        entity.setUpdateTimex(new Date());
//		LfZdryTempEntity tempZdry = new LfZdryTempEntity();
        LfZdryBaseEntity oldZdry = this.getById(entity.getId());
        entity.setSubmitter(bo.getId());
        entity.setLastOperate("transfer");
        try {
            // 临时表过度
            //获取分局名称
            String ssfj = oldZdry.getSsxq();
//			BeanUtils.copyProperties(entity, tempZdry);
            String role = bo.getRoleList().get(0).getId();
            //提交人角色ID
            entity.setSubmitterRoleId(role);
            if (role.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所用户
                //移交市外
                if (1 == entity.getYjsw()) {
                    entity.setGkjb("移交市外");
                    entity.setGkjbCode("10406");
                    entity.setProcessType(35);
                    entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
                } else {
                    if (entity.getSsxq().equals(ssfj)) {
                        entity.setProcessType(3);
                        entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
                    } else {
                        entity.setProcessType(32);
                        entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
                    }
                }
            } else if (role.equals(RoleType.BREACH_REVIEW_DATA.getType()) || role.equals(RoleType.BREACH_DATA.getType())) { // 分局用户
                //移交市外
                if (1 == entity.getYjsw()) {
                    entity.setGkjb("移交市外");
                    entity.setGkjbCode("10406");
                    entity.setProcessType(36);
                    entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
                } else {//分局内移交
                    if (entity.getSsxq().equals(ssfj)) {
                        entity.setProcessType(33);
                        entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
                    } else {
                        entity.setProcessType(34);
                        entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
                    }
                }
            } else if (role.equals(RoleType.OWNER_REVIEW_DATA.getType()) || role.equals(RoleType.OWNER_ORG_DATA.getType()) || role.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 警种用户 ||情报中心
                //移交市外
                if (1 == entity.getYjsw()) {
                    entity.setGkjb("移交市外");
                    entity.setGkjbCode("10406");
                    entity.setProcessType(37);
                } else {
                    entity.setProcessType(33);
                }
                entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
            }
            if (entity.getJzdList() != null && entity.getJzdList().size() > 0) {
                //entity.getJzdList().get(0).setZjzdbj(1);
                //kmZdryHomeService.updateById(entity.getJzdList().get(0));
                entity.setXzzs(entity.getJzdList().get(0).getXzzs());
                entity.setXzzss(entity.getJzdList().get(0).getXzzss());
                entity.setXzzx(entity.getJzdList().get(0).getXzzx());
                entity.setXzz(entity.getJzdList().get(0).getXzz());
                entity.setX(entity.getJzdList().get(0).getX());
                entity.setY(entity.getJzdList().get(0).getY());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean flag = false;
        if (ApproveStatus.COMPLETED.getStatus().equals(entity.getApproveStatus())) {
            //如果是移交类型，则对接收标记赋值1：未接收
            entity.setReceiveFlag(ReceiveFlag.NOT_RECEIVED.getStatus());
            if (null != entity.getJzdList() && entity.getJzdList().size() > 0) {
                for (KmZdryHomeEntity kmZdryHomeEntity : entity.getJzdList()) {
                    if (kmZdryHomeEntity.getZjzdbj() == 1) {
                        kmZdryHomeService.updateById(kmZdryHomeEntity);
                    }
                }
            }
            flag = this.updateById(entity);

//			// 推送重点人员信息
//			this.sendKeyPersonMessage(entity.getId(), "1");

            //清空驳回后的临时表数据
            flag = tempService.removeById(entity.getId());
            /**
             * 如果是移交类型，则对接收移交的分局和派出所发送消息
             * 保存成功后发送消息给对应的用户
             */
            if (flag) {
                this.sendMessage(entity, "transfer");
            }
        } else {
            LfZdryBaseTempEntity tempZdry = new LfZdryBaseTempEntity();
            LfZdryBaseEntity source = this.getById(entity.getId());
            BeanUtils.copyProperties(source, tempZdry);
            //非重新提交，初始数据需要保存
            if (0 == entity.getResubmitFlag() || entity.getResubmitFlag() == null) {
                tempService.save(tempZdry);
            }
            //分局和派出所字段
            LfZdryBaseTempEntity zdry2 = new LfZdryBaseTempEntity();
            BeanUtils.copyProperties(entity, zdry2);
            flag = tempService.updateById(zdry2);
            /**
             * 如果是待处理类型，则对接收移交的分局和派出所发送消息
             * 保存成功后发送消息给对应的用户
             */
            if (flag) {
                this.sendMessage(entity, "stayHandle");
            }
        }

        // 记录审批日志
        String logRecord = specialPersonComponent.getTransferInfo(entity, oldZdry);
        //空字符替换
        if (logRecord.contains("【】")) {
            logRecord = logRecord.replaceAll("【】", "【空】");
        }
        flag = this.operatLog("移交", bo, entity, logRecord, entity.getApprovalOpinion(), exchange);
        return flag;
    }

    @Override
    public boolean reviewProcess(ServerWebExchange exchange, LfZdryBaseTempEntity entity) {
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        String role = bo.getRoleList().get(0).getRoleType();

        //审批方法
        if (role.equals(RoleType.BREACH_REVIEW_DATA.getType())) { // 分局用户
            if ("agree".equals(entity.getReviewState())) {
                if (entity.getProcessType() == 3) {//||entity.getProcessType()==2
                    entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
                } else {
                    entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
                }
                entity.setLastOperate("agree");
            } else {
                entity.setApproveStatus(ApproveStatus.REJECT_REVIEWED.getStatus());
                entity.setLastOperate("reject");
            }
        } else if (role.equals(RoleType.OWNER_REVIEW_DATA.getType())) { // 警种用户
            if ("agree".equals(entity.getReviewState())) {
                entity.setLastOperate("agree");
                entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
            	/*if(entity.getProcessType()==3 || entity.getProcessType()==2) {
            	}else {
            		entity.setApproveStatus(ApproveStatus.INFO_CENTER_REVIEWED.getStatus());
            	}*/
            } else {
                entity.setLastOperate("reject");
                if (RoleType.POLICE_STATION_DATA.getType().equals(entity.getSubmitterRoleId())) {
                    entity.setApproveStatus(ApproveStatus.REJECT_REVIEWED.getStatus());
                } else {
                    //提交人角色为非派出所，则驳回至分局状态
                    entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
                }
            }
        }
        boolean flag = false;
        LfZdryBaseEntity zdry = new LfZdryBaseEntity();
        //被拒绝未完成的重点人员
        LfZdryBaseTempEntity temp = tempService.getById(entity.getId());
        entity.setGkmj(temp.getGkmj());
        entity.setMjid(temp.getMjid());
        entity.setMjlxdh(temp.getMjlxdh());
        entity.setSspcs(temp.getSspcs());
        entity.setSspcsId(temp.getSspcsId());
        BeanUtils.copyProperties(entity, zdry);
        if (!ApproveStatus.COMPLETED.getStatus().equals(entity.getApproveStatus())) {
            tempService.updateById(entity);
            /**
             * 如果是待处理类型，则对接收移交的分局和派出所发送消息
             * 保存成功后发送消息给对应的用户
             */
            if (flag) {
                this.sendMessage(zdry, "stayHandle");
            }
        } else {
            //完成的逻辑
            /**
             * 审核的时候不会传管控民警和民警电话，实体类配置FieldStrategy.IGNORED ;
             * 这里会把空字段更新到基础表 上去；所以这里要二次赋值才可以；
             */
            LfZdryBaseEntity zdry2 = new LfZdryBaseEntity();
            BeanUtils.copyProperties(temp, zdry2);
            if (this.getById(entity.getId()) == null) {
                this.save(zdry2);
            } else {
                this.updateById(zdry2);
            }

            // 推送重点人员信息
            if (zdry.getProcessType() != 1) {
                this.sendKeyPersonMessage(zdry2.getId(), "1");
            }

            //如果是移交类型
            if (zdry.getProcessType() != null && zdry.getProcessType().toString().startsWith("3")) {
                KmZdryHomeEntity tempEntity = kmZdryHomeService.getOne(new QueryWrapper<KmZdryHomeEntity>().lambda().eq(KmZdryHomeEntity::getZdryId, zdry2.getId()).eq(KmZdryHomeEntity::getZjzdbj, 1));
                KmZdryHomeEntity homeEntity = new KmZdryHomeEntity();
                homeEntity.setXzzs(zdry2.getXzzs());
                homeEntity.setXzzss(zdry2.getXzzss());
                homeEntity.setXzzx(zdry2.getXzzx());
                homeEntity.setXzz(zdry2.getXzz());
                homeEntity.setX(zdry2.getX());
                homeEntity.setY(zdry2.getY());
                homeEntity.setY(tempEntity.getId());
                kmZdryHomeService.updateById(homeEntity);
                //则对接收标记赋值1：未接收
                zdry.setReceiveFlag(ReceiveFlag.NOT_RECEIVED.getStatus());
            }
            flag = this.updateById(zdry);
            tempService.removeById(entity.getId());

            /**
             * 如果是移交类型，则对接收移交的分局和派出所发送消息
             * 保存成功后发送消息给对应的用户
             */
            if (zdry.getProcessType() != null && zdry.getProcessType().toString().startsWith("3")) {
                if (flag) {
                    this.sendMessage(zdry, "transfer");
                }
            }
        }
        // 记录审批日志
        flag = this.operatLog("审核", bo, zdry, "agree".equals(entity.getReviewState()) ? "同意审核重点人员" : "同意驳回重点人员", entity.getApprovalOpinion(), exchange);
        return flag;

    }


    @Override
    public IPage<ZdryDto> queryZdryByZrpcsPage(String keyWords, String sspcsId, String ssxqId, Integer offset, Integer size) {
        Page<LfZdryEntity> page = new Page<>(offset, size);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("keyWords", keyWords);

        paramMap.put("sspcsId", sspcsId);
        paramMap.put("ssxqId", ssxqId);
        IPage<ZdryDto> data = this.getBaseMapper().queryZdryByZrpcsPage(page, paramMap);
        handleZdryInfo(data.getRecords());
        return data;
    }

    @Override
    public Mono<DataBuffer> export(String ssxqId, String sspcsId, String exportName) {
        List<ZdryDto> list = this.getBaseMapper().queryExeclExportDataByZrpcs(ssxqId, sspcsId);
        handleZdryInfo(list);

        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
        OutputStream outputStream = dataBuffer.asOutputStream();

        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        CellStyle cellStyleCenter = wb.createCellStyle();
        CellStyle cellStyleLeft = wb.createCellStyle();
        cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
        cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
        cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
        cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
        SXSSFSheet sh = wb.createSheet();
        sh.trackAllColumnsForAutoSizing();
        LocalDate localDate = LocalDate.now();

        int totalSize = 4 + list.size();
        for (int rowNum = 0; rowNum < totalSize; rowNum++) {
            Row row = sh.createRow(rowNum);

            for (int colNum = 0; colNum < 27; colNum++) {
                Cell cell1 = row.createCell(colNum);
                String title = "";
                if (rowNum == 3) {
                    switch (colNum) {
                        case 0: {
                            title = "序号";
                        }
                        break;
                        case 1: {
                            title = "姓名";
                        }
                        break;
                        case 2: {
                            title = "身份证";
                        }
                        break;
                        case 3: {
                            title = "电话号码";
                        }
                        break;
                        case 4: {
                            title = "微信号码";
                        }
                        break;
                        case 5: {
                            title = "qq号码";
                        }
                        break;
                        case 6: {
                            title = "名下车辆号牌";
                        }
                        break;
                        case 7: {
                            title = "实际使用车辆号牌";
                        }
                        break;
                        case 8: {
                            title = "管控责任分局";
                        }
                        break;
                        case 9: {
                            title = "责任派出所";
                        }
                        break;
                        case 10: {
                            title = "责任民警";
                        }
                        break;
                        case 11: {
                            title = "责任民警电话";
                        }
                        break;
                        case 12: {
                            title = "户籍省";
                        }
                        break;
                        case 13: {
                            title = "户籍市";
                        }
                        break;
                        case 14: {
                            title = "户籍县";
                        }
                        break;
                        case 15: {
                            title = "户籍详址";
                        }
                        break;
                        case 16: {
                            title = "实际居住省";
                        }
                        break;
                        case 17: {
                            title = "实际居住市";
                        }
                        break;
                        case 18: {
                            title = "实际居住县";
                        }
                        break;
                        case 19: {
                            title = "实际居住详址";
                        }
                        break;
                        case 20: {
                            title = "人员大类";
                        }
                        break;
                        case 21: {
                            title = "人员细类";
                        }
                        break;
                        case 22: {
                            title = "人员属性";
                        }
                        break;
                        case 23: {
                            title = "风险等级";
                        }
                        break;
                        case 24: {
                            title = "预警处置类别";
                        }
                        break;
                        case 25: {
                            title = "稳控状态";
                        }
                        break;
                        case 26: {
                            title = "备注";
                        }
                        break;
                    }
                    cell1.setCellValue(title);
                } else {
                    if (rowNum > 3) {

                        ZdryDto entity = list.get(rowNum - 4);
                        if (colNum == 0)
                            cell1.setCellValue(rowNum - 3);
                        else {
                            switch (colNum) {
                                case 1: {
                                    cell1.setCellValue(entity.getXm());
                                }
                                break;
                                case 2: {
                                    cell1.setCellValue(entity.getSfzh());
                                }
                                break;
                                case 3: {
                                    cell1.setCellValue(entity.getSjh());
                                }
                                break;
                                case 4: {
                                    cell1.setCellValue(entity.getWx());
                                }
                                break;
                                case 5: {
                                    cell1.setCellValue(entity.getQq());
                                }
                                break;
                                case 6: {
                                    cell1.setCellValue(entity.getMxcph());
                                }
                                break;
                                case 7: {
                                    cell1.setCellValue(entity.getSjsyclhp());
                                }
                                break;
                                case 8: {
                                    cell1.setCellValue(entity.getSsxq());
                                }
                                break;
                                case 9: {
                                    cell1.setCellValue(entity.getSspcs());
                                }
                                break;
                                case 10: {
                                    cell1.setCellValue(entity.getGkmj());
                                }
                                break;
                                case 11: {
                                    cell1.setCellValue(entity.getMjlxdh());
                                }
                                break;
                                case 12: {
                                    cell1.setCellValue(entity.getHjs());
                                }
                                break;
                                case 13: {
                                    cell1.setCellValue(entity.getHjss());
                                }
                                break;
                                case 14: {
                                    cell1.setCellValue(entity.getHjx());
                                }
                                break;
                                case 15: {
                                    cell1.setCellValue(entity.getHjd());
                                }
                                break;
                                case 16: {
                                    cell1.setCellValue(entity.getXzzs());
                                }
                                break;
                                case 17: {
                                    cell1.setCellValue(entity.getXzzss());
                                }
                                break;
                                case 18: {
                                    cell1.setCellValue(entity.getXzzx());
                                }
                                break;
                                case 19: {
                                    cell1.setCellValue(entity.getXzz());
                                }
                                break;
                                case 20: {
                                    cell1.setCellValue(entity.getRylbx());
                                }
                                break;
                                case 21: {
                                    cell1.setCellValue(entity.getXl());
                                }
                                break;
                                case 22: {
                                    SysDictEntity sysDictEntity = service.getEntityByKey("zdry_ryxx",
                                            String.valueOf(entity.getRysx()));
                                    if (null != sysDictEntity) {
                                        cell1.setCellValue(sysDictEntity.getValue());
                                    } else
                                        cell1.setCellValue("");
                                }
                                break;
                                case 23: {
                                    cell1.setCellValue(entity.getGkjb());
                                }
                                break;
                                case 24: {
                                    SysDictEntity sysDictEntity = service.getEntityByKey("zdry_yjczlb",
                                            String.valueOf(entity.getYjczlb()));
                                    if (null != sysDictEntity) {
                                        cell1.setCellValue(sysDictEntity.getValue());
                                    } else
                                        cell1.setCellValue("");
                                }
                                break;
                                case 25: {
                                    cell1.setCellValue(entity.getWkzt());
                                }
                                break;
                                case 26: {
                                    cell1.setCellValue(entity.getBz());
                                }
                                break;
                            }
                        }
                    } else

                        cell1.setCellValue("");
                }
                // 设置单元格样式
                cell1.setCellStyle(cellStyleLeft);
            }
            if (rowNum == 0) {
                sh.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
                sh.getRow(rowNum).getCell(0)
                        .setCellValue(org.springframework.util.StringUtils.isEmpty(exportName)

                                ? "重点人员统计(" + localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ")"
                                : exportName);
                // 设置单元格样式
                sh.getRow(rowNum).getCell(0).setCellStyle(cellStyleCenter);
            }
            if (rowNum == 1) {

                sh.addMergedRegion(new CellRangeAddress(1, 2, 0, 3));
                sh.getRow(rowNum).getCell(0)
                        .setCellValue("填报日期： " + localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }
            if (rowNum == 2) {
                // sh.addMergedRegion(new CellRangeAddress(2,3,0,3));
                // sh.getRow(rowNum).getCell(0).setCellValue("本单位涉及人员" + list.size() + "名：在控 " +
                // zkCount + " 人,失控 " + skCount + " 人,未上报 " + wsbCount + " 人");
                sh.getRow(1).getCell(4).setCellValue("单位一把手签字：");
                sh.addMergedRegion(new CellRangeAddress(1, 2, 4, 9));
            }
        }
        for (int i = 0; i < totalSize; i++) {
            sh.autoSizeColumn(i, true);
        }
        try {
            wb.write(outputStream);
        } catch (IOException e) {
            log.error("error == >{}", e.getMessage());
        } finally {
            try {
                wb.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error("error == >{}", e.getMessage());
            }
        }
        return Mono.just(dataBuffer);

    }

    @Override
    public boolean updateWkztById(String id, String wkzt) {
        LfZdryBaseEntity zdry = new LfZdryBaseEntity();
        zdry.setId(id);
        zdry.setWkzt(wkzt);
        return this.updateById(zdry);
    }

    @Override
    public boolean updateAppealById(String id, String appeal) {
        UpdateWrapper<LfZdryBaseEntity> wrapper = new UpdateWrapper<LfZdryBaseEntity>();
        wrapper.eq("id", id);
        wrapper.set("appeal", appeal); //诉求字段
        return this.update(wrapper);
    }

    @Override
    public boolean updateTxBySfzh(String sfzh) {
        UpdateWrapper<LfZdryBaseEntity> wrapper = new UpdateWrapper<LfZdryBaseEntity>();
        wrapper.eq("sfzh", sfzh);
        wrapper.set("tx", sfzh); //诉求字段
        return this.update(wrapper);
    }

    @Override
    public Integer updateZdryBySfzh(LfZdryBaseEntity zdry) {
        return this.getBaseMapper().updateZdryBySfzh(zdry);
    }


    @Override
    public Object getZdryCountBySfzh(String sfzh) {
        Integer zdryCount = this.count(new QueryWrapper<LfZdryBaseEntity>().lambda().eq(LfZdryBaseEntity::getSfzh, sfzh));
        Integer zdryTempCount = lfZdryBaseTempService.count(new QueryWrapper<LfZdryBaseTempEntity>().lambda().eq(LfZdryBaseTempEntity::getSfzh, sfzh));
        return zdryCount + zdryTempCount;
    }

    @Override
    public List<Map<String, Object>> getEveryProvinceZdryNum() {
        return this.getBaseMapper().getEveryProvinceZdryNum();
    }

    @Override
    public List<Map<String, Object>> getCityZdryNumByProvinceCode(String code) {
        return this.getBaseMapper().getCityZdryNumByProvinceCode(code);
    }

    @Override
    public List<Map<String, Object>> getCountryZdryNumByCityCode(String code) {
        return this.getBaseMapper().getCountryZdryNumByCityCode();
    }

    @Override
    public Mono<DataBuffer> exportZdryByHjdAndXzz(List<String> sfzhs, String exportName) {
        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
        OutputStream outputStream = dataBuffer.asOutputStream();
        // 每次写100行数据，就刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);

        try {
            CellStyle cellStyleCenter = wb.createCellStyle();
            CellStyle cellStyleLeft = wb.createCellStyle();
            cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
            cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
            cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
            cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
            //加载数据的地方
            List<ZdryDto> data = this.getBaseMapper().queryZdryByHjdAndXzzData(sfzhs);
            handleZdryInfo(data);
            for (ZdryDto zdry : data) {
                SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb", zdry.getYjczlb().toString());
                if (null != yjczlbdictEntity)
                    zdry.setYjczlbName(yjczlbdictEntity.getValue());
                SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx", zdry.getRysx().toString());
                if (null != rysxdictEntity)
                    zdry.setRysxName(rysxdictEntity.getValue());
            }
            Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/zdryInfoHjdAndXzz.json", Map.class);
            ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, data, ZdryDto.class, proTitleMap, "重点人员信息");
            wb.write(outputStream);
        } catch (Exception e) {
            log.error("导出execl时发生异常：======>{}", e.getMessage());
        } finally {
            try {
                wb.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error("关闭流时发生异常：======> {}", e.getMessage());
            }
        }
        return Mono.just(dataBuffer);
    }

    @Override
    public Object queryProvinceTx(ServerWebExchange exchange, LfZdryQO qo) {
        setUpAuthority(exchange, qo); //设置权限
        return this.getBaseMapper().queryProvinceTx(qo);
    }

    @Override
    public Object queryCityTx(ServerWebExchange exchange, LfZdryQO qo) {
        setUpAuthority(exchange, qo); //设置权限
        return this.getBaseMapper().queryCityTx(qo);
    }

    @Override
    public IPage<ZdryDto> queryProvinceAndCityTxList(ServerWebExchange exchange, LfZdryQO qo) {
        setUpAuthority(exchange, qo); //设置权限
        Page<ZdryDto> page = new Page<>(qo.getStart(), qo.getSize());
        IPage<ZdryDto> result = this.getBaseMapper().queryProvinceAndCityTxList(page, qo);
        handleZdryInfo(result.getRecords());
        for (ZdryDto z : result.getRecords()) {
            //人员属性
            SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx", String.valueOf(z.getRysx()));
            if (null != rysxdictEntity) {
                z.setRysxName(rysxdictEntity.getValue());
            }

            //预警处置级别
            SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb", String.valueOf(z.getYjczlb()));
            if (null != yjczlbdictEntity) {
                z.setYjczlbName(yjczlbdictEntity.getValue());
            }
        }
        return result;
    }

    @Override
    public Mono<DataBuffer> exportZdryProvinceAndCityQxData(LfZdryQO qo, String exportName, ServerWebExchange exchange) {
        DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
        OutputStream outputStream = dataBuffer.asOutputStream();
        // 每次写100行数据，就刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);

        try {
            CellStyle cellStyleCenter = wb.createCellStyle();
            CellStyle cellStyleLeft = wb.createCellStyle();
            cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
            cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
            cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
            cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
            //加载数据的地方
            setUpAuthority(exchange, qo); //设置权限
            List<ZdryDto> result = this.getBaseMapper().queryProvinceAndCityTxExportData(qo);
            handleZdryInfo(result);

            for (ZdryDto z : result) {
                //人员属性
                SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx", String.valueOf(z.getRysx()));
                if (null != rysxdictEntity) {
                    z.setRysxName(rysxdictEntity.getValue());
                }

                //预警处置级别
                SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb", String.valueOf(z.getYjczlb()));
                if (null != yjczlbdictEntity) {
                    z.setYjczlbName(yjczlbdictEntity.getValue());
                }

                z.setXzz(z.getXzzs() + "//" + z.getXzzss() + "//" + z.getXzzx() + "//" + z.getXzz());
            }

            Map<String, String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/zdryInfoHjdAndXzz.json", Map.class);
            ExeclUtil.genExcel(wb, cellStyleCenter, cellStyleLeft, result, ZdryDto.class, proTitleMap, "重点人员迁徙信息");
            wb.write(outputStream);
        } catch (Exception e) {
            log.error("导出execl时发生异常：======>{}", e.getMessage());
        } finally {
            try {
                wb.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {

                log.error("关闭流时发生异常：======> {}", e.getMessage());
            }
        }
        return Mono.just(dataBuffer);
    }

    @Override
    public List<Map<String, Object>> queryZdryList(ServerWebExchange exchange, LfZdryQO qo) {
        setUpAuthority(exchange, qo); //设置权限
        List<Map<String, Object>> result = mapper.queryZdryList(qo);
        return result;
    }

    @Override
    public IPage<ZdryDto> queryZdry(Map<String, Object> paramMap) {
        Page<ZdryDto> page = new Page<>((int) paramMap.get("offset"), (int) paramMap.get("pageSize"));
        IPage<ZdryDto> result = this.getBaseMapper().queryZdry(page, (List<String>) paramMap.get("sfzhs"));
        //this.page(page,new QueryWrapper<LfZdryEntity>().lambda().in(LfZdryEntity::getSfzh,(List<String>)paramMap.get("sfzhs")));
        handleZdryInfo(result.getRecords());
        for (ZdryDto z : result.getRecords()) {
            //人员属性
            SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx", String.valueOf(z.getRysx()));
            if (null != rysxdictEntity) {
                z.setRysxName(rysxdictEntity.getValue());
            }

            //预警处置级别
            SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb", String.valueOf(z.getYjczlb()));
            if (null != yjczlbdictEntity) {
                z.setYjczlbName(yjczlbdictEntity.getValue());
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> queryPushZdryInfo(Integer offset, Integer pageSize) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Page<ZdryDto> page = new Page<>(offset, pageSize);
            IPage<ZdryDto> result = this.getBaseMapper().queryPushZdryInfo(page);
            handleZdryInfo(result.getRecords());
            resultMap.put("total", result.getTotal());
            List<Map<String, Object>> records = new ArrayList<>();
            for (ZdryDto zdry : result.getRecords()) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", zdry.getXm());
                map.put("province", zdry.getHjs());
                map.put("sex", zdry.getXb());
                map.put("tel", zdry.getSjh());
                map.put("address", zdry.getXzz());
                map.put("IDCard", zdry.getSfzh());
                map.put("rydl", zdry.getRylbx());
                map.put("ryxl", zdry.getXl());
                map.put("policeStation", zdry.getSspcs());
                map.put("policeStationId", zdry.getSspcsId());
                map.put("policeman", zdry.getGkmj());
                map.put("policemanPhone", zdry.getMjlxdh());
                map.put("domicile", zdry.getHjd());
                map.put("xzz", zdry.getJzdList());
                records.add(map);
            }
            resultMap.put("records", records);
        } catch (Exception e) {
            log.error("推送接口发生异常=======》{}", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 概览接口
     *
     * @param cid
     * @param code
     * @param regionId
     * @return
     */
    @Override
    public List<Map<String, String>> getCount(String cid, String code, String regionId) {
        if (cid == null) throw new BusinessException(500, "cid参数错误");
        List<OrganizationDto> organizationDtos = cacheableService.getUpOrgById(regionId);
        //OrganizationDto org = getOrganizationByCondition(organizationDtos,"支队");
        StringBuilder sb = new StringBuilder();
        switch (code) {
            case "2": {
                OrganizationDto fjOrg = getOrganizationByCondition(organizationDtos, "分局");
                if (null != fjOrg) sb.append(fjOrg.getId());
                OrganizationDto sjOrg = getOrganizationByCondition(organizationDtos, "市局");
                if (null != sjOrg) sb.append(sjOrg.getId());
                OrganizationDto xjOrg = getOrganizationByCondition(organizationDtos, "县局");
                if (null != xjOrg) sb.append(xjOrg.getId());
            }
            break;
            case "3": {
                OrganizationDto org = getOrganizationByCondition(organizationDtos, "派出所");
                if (null != org) sb.append(org.getId());
            }
            break;
            case "4": {
                OrganizationDto org = getOrganizationByCondition(organizationDtos, "支队");
                if (null != org) sb.append(org.getShortName());
            }
            break;
        }

        List<Map<String, String>> resultMap = null;
        switch (cid) {
            case "1": {
                if (!code.equals("4")) { // 情报中心 分局 派出所
                    resultMap = this.getBaseMapper().getCountWkztForQbzxAndSsxqAndSspcs(code, sb.toString());
                } else { // 警种
                    resultMap = this.getBaseMapper().getCountWkztForZrbm(code, sb.toString());
                }
            }
            break;
            case "2": {
                if (!code.equals("4")) { // 情报中心 分局 派出所
                    resultMap = this.getBaseMapper().getCountRegionForQbzxAndSsxqAndSspcs(code, sb.toString());
                } else {
                    resultMap = this.getBaseMapper().getCountRegionForZrbm(code, sb.toString());
                }
            }
            break;
            case "3": { //管控级别的查询
                if (!code.equals("4")) { // 情报中心 分局 派出所
                    resultMap = this.getBaseMapper().getCountGkjbForQbzxAndSsxqAndSspcs(code, regionId);
                } else { // 警种
                    resultMap = this.getBaseMapper().getCountGkjbForZrbm(code, sb.toString());
                }
            }
            break;
            case "4": {
                // 情报中心 分局 派出所
                resultMap = this.getBaseMapper().getCountRylb(code, sb.toString());
            }
            break;
        }
        return resultMap;
    }

    @Override
    public List<SpecialPersonStatisticsDataVO> getSpecialPersonStatistics(LfZdryQO qo) {
//		List<String> list = new ArrayList<>();
//		if (!StringUtils.isEmpty(rangeType) && !StringUtils.isEmpty(rangeVal)) {
//			list.addAll(Arrays.asList(rangeVal.split(",")));
//		}
//		List<String> zrdwList = new ArrayList<>();
//		if (!StringUtils.isEmpty(zrdws) && !StringUtils.isEmpty(zrdws)) {
//			zrdwList.addAll(Arrays.asList(zrdws.split(",")));
//		}
        return this.getBaseMapper().getSpecialPersonStatistics(qo);
    }

    /**
     * 处理重点人员信息
     */
    private void handleZdryInfo(List<ZdryDto> data) {
        if (null != data && data.size() > 0) {
            for (ZdryDto zdry : data) {
                StringBuilder dhhm = new StringBuilder();
                StringBuilder wx = new StringBuilder();
                StringBuilder qq = new StringBuilder();
                StringBuilder mxcph = new StringBuilder();
                StringBuilder sjcph = new StringBuilder();
                if (null != zdry.getAssistList() && zdry.getAssistList().size() > 0) {
                    Map<Integer, List<KmZdryAssistEntity>> assists = zdry.getAssistList().stream().collect(Collectors.groupingBy(KmZdryAssistEntity::getInfoType));
                    List<KmZdryAssistEntity> dh = assists.get(ZdryAssistType.TEL.getType());
                    if (null != dh && dh.size() > 0) {
                        dh.forEach(e -> {
                            if (dhhm.length() > 0) dhhm.append("/").append(e.getInfoValue());
                            else dhhm.append(e.getInfoValue());
                        });
                    }
                    List<KmZdryAssistEntity> w = assists.get(ZdryAssistType.WX.getType());
                    if (null != w && w.size() > 0) {
                        w.forEach(e -> {
                            if (wx.length() > 0) wx.append("/").append(e.getInfoValue());
                            else wx.append(e.getInfoValue());
                        });
                    }
                    List<KmZdryAssistEntity> q = assists.get(ZdryAssistType.QQ.getType());
                    if (null != q && q.size() > 0) {
                        q.forEach(e -> {
                            if (qq.length() > 0) qq.append("/").append(e.getInfoValue());
                            else qq.append(e.getInfoValue());
                        });
                    }
                    List<KmZdryAssistEntity> mx = assists.get(ZdryAssistType.MXCPH.getType());
                    if (null != mx && mx.size() > 0) {
                        mx.forEach(e -> {
                            if (mxcph.length() > 0) mxcph.append("/").append(e.getInfoValue());
                            else mxcph.append(e.getInfoValue());
                        });
                    }
                    List<KmZdryAssistEntity> sj = assists.get(ZdryAssistType.SJCPH.getType());
                    if (null != sj && sj.size() > 0) {
                        sj.forEach(e -> {
                            if (sjcph.length() > 0) sjcph.append("/").append(e.getInfoValue());
                            else sjcph.append(e.getInfoValue());
                        });
                    }
                }
                zdry.setSjh(dhhm.toString());
                zdry.setWx(wx.toString());
                zdry.setQq(qq.toString());
                zdry.setMxcph(mxcph.toString());
                zdry.setSjsyclhp(sjcph.toString());
                //处理居住地
                List<KmZdryHomeEntity> homes = zdry.getJzdList();
                StringBuilder xzzs = new StringBuilder();
                StringBuilder xzzss = new StringBuilder();
                StringBuilder xzzx = new StringBuilder();
                StringBuilder xzz = new StringBuilder();
                if (null != homes && homes.size() > 0) {
                    homes.forEach(e -> {
                        if (xzzs.length() > 0) xzzs.append("/").append(e.getXzzs());
                        else xzzs.append(e.getXzzs());
                        if (xzzss.length() > 0) xzzss.append("/").append(e.getXzzss());
                        else xzzss.append(e.getXzzss());
                        if (xzzx.length() > 0) xzzx.append("/").append(e.getXzzx());
                        else xzzx.append(e.getXzzx());
                        if (xzz.length() > 0) xzz.append("/").append(e.getXzz());
                        else xzz.append(e.getXzz());
                    });
                }
                zdry.setXzzs(xzzs.toString());
                zdry.setXzzss(xzzss.toString());
                zdry.setXzzx(xzzx.toString());
                zdry.setXzz(xzz.toString());

                // 人员大类 人员小类
                List<KmZdryTypeEntity> zt = zdry.getTypeList();
                StringBuilder dl = new StringBuilder();
                StringBuilder xl = new StringBuilder();
                StringBuilder zrbm = new StringBuilder();
                if (null != zt && zt.size() > 0) {
                    zt.forEach(e -> {
                        if (dl.length() > 0) dl.append("/").append(e.getRylb());
                        else dl.append(e.getRylb());
                        if (xl.length() > 0) xl.append("/").append(e.getXl());
                        else xl.append(e.getXl());
                        if (zrbm.length() > 0) zrbm.append("/").append(e.getZrbm());
                        else zrbm.append(e.getZrbm());
                    });
                }
                zdry.setRylbx(dl.toString());
                zdry.setXl(xl.toString());
                zdry.setZrbm(zrbm.toString());
            }
        }
    }

    /**
     * 在查询条件中设置  权限相关的参数
     *
     * @param exchange
     * @param qo
     */
    public void setUpAuthority(ServerWebExchange exchange, LfZdryQO qo) {

        try {
            Map<String, String> regiones = cacheableService.getAllRegionInfo("allRegion");
            List<String[]> hjssxList = new ArrayList<String[]>();
            if (qo.getHjssxList() != null) {
                for (String[] ssxs : qo.getHjssxList()) {
                    String[] ssxChar = new String[3];
                    for (int i = 0; i < ssxs.length; i++) {
                        ssxChar[i] = regiones.get(ssxs[i]);
                    }
                    hjssxList.add(ssxChar);
                }
                qo.setHjssxList(hjssxList);
            }
            // 权限相关代码
            AccountBo bo = requestUtils.getCurrentUser(exchange);
            if (bo == null) {
                throw new BusinessException(10019, "此账号已在别处登录，请查证");
            }
            String roleType = bo.getRoleList().get(0).getRoleType();
            String orgName = bo.getOrganizationBo().getShortName();
            List<OrganizationDto> organizationDtos = cacheableService.getUpOrgById(bo.getOrganizationBo().getId());

            // getOrgName(bo.getOrgId());
            // 1、管理员、市局情报中心,不加判断条件
            // 2、市局各警种
            // 角色类型："管理员", "0")"市局情报中心", "1"), "市局警种", "2"),"分局", "3"),"派出所", "4")
            // 审批状态：0：待分局审批,1：待警种审核,2：已驳回,3：已完成, 4：上报
            if (roleType.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 1:市局情报中心
                qo.setSsxqList(qo.getQueryList());
            } else if (roleType.equals(RoleType.OWNER_REVIEW_DATA.getType())
                    || roleType.equals(RoleType.OWNER_ORG_DATA.getType())) { // 5:市局警种和2:市局警种审核
                OrganizationDto org = getOrganizationByCondition(organizationDtos, "支队");
                if (null != org) qo.setZrbm(org.getShortName());
                qo.setSsxqList(qo.getQueryList());
            } else if (roleType.equals(RoleType.BREACH_REVIEW_DATA.getType())
                    || roleType.equals(RoleType.BREACH_DATA.getType())) { // 6:分局 和 3:分局审核
                OrganizationDto org1 = getOrganizationByCondition(organizationDtos, "分局");
                if (null != org1) qo.setSsxq(org1.getShortName());
                OrganizationDto org2 = getOrganizationByCondition(organizationDtos, "县局");
                if (null != org2) qo.setSsxq(org2.getShortName());
                OrganizationDto org3 = getOrganizationByCondition(organizationDtos, "市局");
                if (null != org3) qo.setSsxq(org3.getShortName());
                log.info("============qo=========:" + qo);
                /*
                 * if(qo.getQueryList()!=null&&!qo.getQueryList().contains("其他")) { }
                 */
                if (null != qo.getQueryList()) {

                    List<String> list = new ArrayList<String>();
                    for (String pcs : qo.getQueryList()) {
                        list.add(pcs);//qo.getSsxq() +
                    }
                    qo.setSspcsList(list);
                }

            } else if (roleType.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所4
                OrganizationDto org = getOrganizationByCondition(organizationDtos, "派出所");
                if (null != org) {
                    //		qo.setSspcs(org.getShortName());
                    qo.setCode(org.getRegionId());
                }
                qo.setMjList(qo.getQueryList());
            }

        } catch (BusinessException e) {
            log.error("权限参数异常或者筛选参数异常：======>{}", e.getMessage());
            if ("此账号已在别处登录，请查证".equals(e.getMessage())) {
                throw new BusinessException(10019, "此账号已在别处登录，请查证");
            }
        }
    }

    @Override
    public Map<String, Object> queryWkztCount(ServerWebExchange exchange, LfZdryQO qo) {
        setUpAuthority(exchange, qo);
        Map<String, Object> result = new HashMap<String, Object>() {
            {
                put("Searching", 0l);
                put("Stabilized", 0l);
                put("OutOfControl", 0l);
                put("other", 0l);
            }
        };
        List<Map<String, Object>> wkztes = this.getBaseMapper().queryWkztCount(qo);
        if (null != wkztes && wkztes.size() > 0) {
            long otherCount = 0l;
            for (Map<String, Object> map : wkztes) {
                if (map.get("wkzt").equals("其他")) {
                    otherCount += Long.parseLong(map.get("count").toString());
                } else {
                    if (map.get("wkzt").equals("查找中"))
                        result.put("Searching", Long.parseLong(map.get("count").toString()) + Long.parseLong(result.get("Searching").toString()));
                    if (map.get("wkzt").equals("已稳控"))
                        result.put("Stabilized", Long.parseLong(map.get("count").toString()) + Long.parseLong(result.get("Stabilized").toString()));
                    if (map.get("wkzt").equals("失控"))
                        result.put("OutOfControl", Long.parseLong(map.get("count").toString()) + Long.parseLong(result.get("OutOfControl").toString()));
                }
            }
            result.put("other", otherCount);
        }
        return result;
    }

    @Override
    public List<SpecialPersonStatisticsDataVO> getSpecialPersonStatisticsForPoliceCategory(LfZdryQO qo) {
        return this.getBaseMapper().getSpecialPersonStatisticsForPoliceCategory(qo);
    }

    @Override
    public List<LfZdryBaseEntity> findZdryGatherList(List<String> sfzhs) {
        return this.getBaseMapper().findZdryGatherList(sfzhs);
    }

    /**
     * 根据条件查询对应单位
     *
     * @param organizationDtos
     * @param con
     * @return
     */
    private OrganizationDto getOrganizationByCondition(List<OrganizationDto> organizationDtos, String con) {
        OrganizationDto result = null;
        for (OrganizationDto org : organizationDtos) {
            if (org.getShortName().indexOf(con) >= 0) {
                result = org;
                break;
            }
        }
        return result;
    }

    /**
     * 地址转经纬度
     *
     * @param address
     */
    @Override
    public Map<String, String> getCoordinate(AddressQO address) {
        long startTime = new Date().getTime();
        Map<String, String> resultMap = new HashMap<>();
        // 获取现住址地的经纬度
        try {
            Map<String, String> xzzAdress = specialPersonService.searchLngLat(address.getProvice(), address.getCity(), address.getRegion(), address.getDetailAddress());
            if (null != xzzAdress) {
                resultMap.put("x", xzzAdress.get("x"));
                resultMap.put("y", xzzAdress.get("y"));
            }

        } catch (Exception e) {
            log.debug("查询现住址经纬度时发生错误");
        }
        long endTime = new Date().getTime();
        log.info("执行查询花费：" + (endTime - startTime) / 1000);
        return resultMap;
    }

    @Override
    public IPage<LfZdryBaseTempEntity> queryPageStatyReviewedList(LfZdryQO qo, ServerWebExchange exchange) {
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        Page<LfZdryEntity> page = new Page<>(qo.getStart(), qo.getSize());
        qo.setRylbxList(ListUtils.removeNullElement(qo.getRylbxList()));
        qo.setSfzkList(ListUtils.removeNullElement(qo.getSfzkList()));
        qo.setZrbmList(ListUtils.removeNullElement(qo.getZrbmList()));
        qo.setSsxqList(ListUtils.removeNullElement(qo.getSsxqList()));
        qo.setSsxqIdList(ListUtils.removeNullElement(qo.getSsxqIdList()));
        qo.setGkjbxList(ListUtils.removeNullElement(qo.getGkjbxList()));
        qo.setMjidList(ListUtils.removeNullElement(qo.getMjidList()));
        qo.setSspcsList(ListUtils.removeNullElement(qo.getSspcsList()));
        qo.setRylyList(ListUtils.removeNullElement(qo.getRylyList()));
        // qo.setApproveStatus(ApproveStatus.COMPLETED.getStatus().toString());
        //新增户籍省市县查询
        Map<String, String> regiones = cacheableService.getAllRegionInfo("allRegion");
        List<String[]> hjssxList = new ArrayList<String[]>();
        for (String[] ssxs : qo.getHjssxList()) {
            String[] ssxChar = new String[ssxs.length];
            for (int i = 0; i < ssxs.length; i++) {
                ssxChar[i] = regiones.get(ssxs[i]);
            }
            hjssxList.add(ssxChar);
        }
        qo.setHjssxList(hjssxList);
        // 权限相关代码
        String roleType = bo.getRoleList().get(0).getRoleType();
        String orgName = bo.getOrganizationBo().getShortName();
        qo.setSubmitter(bo.getId());
        // getOrgName(bo.getOrgId());
        // 1、管理员、市局情报中心,不加判断条件
        // 2、市局各警种
        // 角色类型："管理员", "0")"市局情报中心", "1"), "市局警种", "2"),"分局", "3"),"派出所", "4")
        // 审批状态：0：已驳回,1：待分局审批,2：待警种审核,3：待情报中心审核, 4：审核完毕
        List<OrganizationDto> organizationDtos = cacheableService.getUpOrgById(bo.getOrganizationBo().getId());
        if (roleType.equals(RoleType.OWNER_REVIEW_DATA.getType())
                || roleType.equals(RoleType.OWNER_ORG_DATA.getType())) { // 5:市局警种和2:市局警种审核
            OrganizationDto org = getOrganizationByCondition(organizationDtos, "支队");
            if (null != org) qo.setZrbm(org.getShortName());
            qo.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
            qo.setSsxqList(qo.getQueryList());
        } else if (roleType.equals(RoleType.BREACH_REVIEW_DATA.getType())
                || roleType.equals(RoleType.BREACH_DATA.getType())) { // 6:分局 和 3:分局审核
            OrganizationDto org1 = getOrganizationByCondition(organizationDtos, "分局");
            if (null != org1) qo.setSsxq(org1.getShortName());
            OrganizationDto org2 = getOrganizationByCondition(organizationDtos, "县局");
            if (null != org2) qo.setSsxq(org2.getShortName());
            OrganizationDto org3 = getOrganizationByCondition(organizationDtos, "市局");
            if (null != org3) qo.setSsxq(org3.getShortName());
            //qo.setSsxq(orgName);
            qo.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
            // 右下角管辖派出所 ==== 派出所不为空
            /*
             * if(qo.getQueryList()!=null&&!qo.getQueryList().contains("其他")) { }
             */
            List<String> list = new ArrayList<String>();
            for (String pcs : qo.getQueryList()) {
                list.add(pcs);//qo.getSsxq() +
            }
            qo.setSspcsList(list);
        } else if (roleType.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所4
            OrganizationDto org = getOrganizationByCondition(organizationDtos, "派出所");
            if (null != org) qo.setSspcs(org.getShortName());
            //qo.setSspcs(orgName);
            qo.setApproveStatus(ApproveStatus.REJECT_REVIEWED.getStatus());
            qo.setMjList(qo.getQueryList());

        }

        return tempZdryMapper.queryPage(page, qo);
    }

    /**
     * 发送消息
     *
     * @param entity
     * @param type   类型：transfer,移交类消息；stayHandle,待处理消息
     */
    public void sendMessage(LfZdryBaseEntity entity, String type) {
        //添加成功后发送websocket
        List<String> tokens = this.findUserListByOrgName(entity, type);
        if ("transfer".equals(type)) {
            if (null != tokens)
                webSocketUtils.sendWebsockMessageToUser(tokens,
                        Arrays.asList("新增移交消息"), SocketType.ZDRRYJJSXX.getCode());
        } else {
//			List<String> tokens = this.findUserListByOrgName(entity,type);
            if (null != tokens)
                webSocketUtils.sendWebsockMessageToUser(tokens,
                        Arrays.asList("待处理信息"), SocketType.ZDRDCLXX.getCode());
        }
    }

    public List<String> findUserListByOrgName(LfZdryBaseEntity entity, String type) {
        try {
            List<String> resultList = new ArrayList<>();
            List<UserTypeInfo> users = new ArrayList<>();  //当前链接websocket的所有用户
            Set<String> keies = redisUtil.keys("kmzdry_websocket_*");
            for (String key : keies) {
                String s = redisUtil.get(key).toString();
                users.add(getUserTypeInfo(s));
            }
            for (UserTypeInfo u : users) {
                if (u.getRole() == null) continue;
                switch (u.getRole()) {
                /* 判断是不是情报中心
                    case "1":resultList.add(u.getToken());break; // 情报中心*/
                    // 审批状态(0：已驳回，1：待分局审批/已驳回至分局，2：待警种审核，3：待情报中心审核，4：已完成)
                    case "2": { //警种  待处理时发消息
                        if (null != entity.getZrbm() && type.equals("stayHandle")) {
                            if ("2".equals(entity.getApproveStatus())) {
                                if (entity.getZrbm().equals(u.getName()))
                                    resultList.add(u.getToken());
                            }
                        }
                    }
                    break;
                    case "3": { //分局  待处理和移交都发消息
                        if (null != entity.getSsxq()) {
                            if ("1".equals(entity.getApproveStatus())) {
                                if (entity.getSsxq().equals(u.getName()))
                                    resultList.add(u.getToken());
                            }
                        }
                    }
                    break;
                    case "4": { //派出所  移交发消息
                        if (null != entity.getSspcs()) {
                            if ("0".equals(entity.getApproveStatus()) || type.equals("transfer")) {
                                if (entity.getSspcs().equals(u.getName()))
                                    resultList.add(u.getToken());
                            }
                        }
                    }
                    break;
                }

            }
            return resultList;
        } catch (Exception e) {
            log.error("查询推送token时发生异常：{}", e.getMessage());
            return null;
        }
    }


    private UserTypeInfo getUserTypeInfo(String s) {
        try {
            UserTypeInfo userTypeInfo = new UserTypeInfo();
            String[] array = s.substring(s.indexOf("{") + 1, s.lastIndexOf("}")).split(",");
            for (String obj : array) {
                switch (obj.split("=")[0].trim()) {
                    case "token":
                        userTypeInfo.setToken(obj.split("=")[1].trim());
                        break;
                    case "id":
                        userTypeInfo.setId(obj.split("=")[1].trim());
                        break;
                    case "role":
                        userTypeInfo.setRole(obj.split("=")[1].trim());
                        break;
                    case "name":
                        userTypeInfo.setName(obj.split("=")[1].trim());
                        break;
                }
            }
            return userTypeInfo;
        } catch (Exception e) {
            log.error("websocket 链接参数不正确。");
            return null;
        }
    }


    @Override
    public Integer getNotReceviedCount(ServerWebExchange exchange) {
        // TODO Auto-generated method stub
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        String orgType = "";
        if ("4".equals(bo.getRoleList().get(0).getRoleType())) { //派出所
            orgType = "sspcs";
        } else if ("3".equals(bo.getRoleList().get(0).getRoleType()) || "6".equals(bo.getRoleList().get(0).getRoleType())) { //分局
            orgType = "ssxq";
        }
        Integer count = 0;
        if (StringUtils.isNotEmpty(orgType)) {
            count = this.count(new QueryWrapper<LfZdryBaseEntity>().eq("receive_flag", 1).eq(orgType, bo.getOrganizationBo().getShortName()));
        }
        return count;
    }

    @Override
    public Integer getStayHandleCount(ServerWebExchange exchange) {
        // TODO Auto-generated method stub
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        List<OrganizationDto> organizationDtos = cacheableService.getUpOrgById(bo.getOrganizationBo().getId());
        String orgType = "";
        String shortName = "";
        // 0:驳回至派出所，1：待分局审批/已驳回至分局，2：待警种审核
        String status = "";
        if ("2".equals(bo.getRoleList().get(0).getRoleType())) { //警种审核
            orgType = "zrbm";
            OrganizationDto org = getOrganizationByCondition(organizationDtos, "支队");
            shortName = org.getShortName();
            status = "2";
        } else if ("3".equals(bo.getRoleList().get(0).getRoleType())) { //分局审核
            orgType = "ssxq";
            OrganizationDto fjOrg = getOrganizationByCondition(organizationDtos, "分局");
            if (null != fjOrg) shortName = fjOrg.getShortName();
            OrganizationDto xjOrg = getOrganizationByCondition(organizationDtos, "县局");
            if (null != xjOrg) shortName = xjOrg.getShortName();
            OrganizationDto sjOrg = getOrganizationByCondition(organizationDtos, "市局");
            if (null != sjOrg) shortName = sjOrg.getShortName();
            status = "1";
        }
        Integer count = 0;
        if (StringUtils.isNotEmpty(orgType)) {
            count = tempService.count(new QueryWrapper<LfZdryBaseTempEntity>().eq("approve_status", status).eq(orgType, shortName));
        }
        return count;
    }

    @Override
    public Map<String, String> findZdryBySfzhAndSjh(String idCard, String phone) {
        return this.getBaseMapper().findZdryBySfzhAndSjh(idCard, phone);
    }

    @Override
    public boolean sendKeyPersonMessage(String personId, String gxlx) {
        if (StringUtils.isEmpty(personId) || StringUtils.isEmpty(gxlx)) {
            throw new BusinessException(500, "参数不能为空");
        }
        Map<String, Object> keyPerson = mapper.getkeyPersonByPersonId(personId);
        // 推送重点人员数据
        ZdryEntity zdryEntity = new ZdryEntity();
        zdryEntity.setId(keyPerson.containsKey("id") ? keyPerson.get("id").toString() : "");
        zdryEntity.setRylb_code(keyPerson.containsKey("rylb_code") ? keyPerson.get("rylb_code").toString() : "");
        zdryEntity.setXl_code(keyPerson.containsKey("xl_code") ? keyPerson.get("xl_code").toString() : "");
        zdryEntity.setXm(keyPerson.containsKey("xm") ? keyPerson.get("xm").toString() : "");
        zdryEntity.setXb(keyPerson.containsKey("xb") ? keyPerson.get("xb").toString() : "");
        zdryEntity.setMz(keyPerson.containsKey("mz") ? keyPerson.get("mz").toString() : "");
        zdryEntity.setSfzh(keyPerson.containsKey("sfzh") ? keyPerson.get("sfzh").toString() : "");
        zdryEntity.setHjd(keyPerson.containsKey("hjd") ? keyPerson.get("hjd").toString() : "");
        zdryEntity.setJg(keyPerson.containsKey("jg") ? keyPerson.get("jg").toString() : "");
        zdryEntity.setSjh(keyPerson.containsKey("sjh") ? keyPerson.get("sjh").toString() : "");
        zdryEntity.setCreate_time(keyPerson.containsKey("create_time") ? keyPerson.get("create_time").toString() : null);
        zdryEntity.setUpdate_time(keyPerson.containsKey("update_time") ? keyPerson.get("update_time").toString() : null);
        zdryEntity.setGk_jb_code(keyPerson.containsKey("gk_jb_code") ? keyPerson.get("gk_jb_code").toString() : "");
        zdryEntity.setXzz(keyPerson.containsKey("xzz") ? keyPerson.get("xzz").toString() : "");
        zdryEntity.setGxlx(gxlx);
        zdryEntity.setTx(keyPerson.containsKey("tx") ? keyPerson.get("tx").toString() : "");
        //照片为空时不推送kafka
        if (null != zdryEntity.getTx() && !"".equals(zdryEntity.getTx())) {
            String tx = zdryEntity.getTx();
            if (tx.contains("zdry")) {
                zdryEntity.setTx(kafkaTxUrl + ":10001/" + keyPerson.get("tx").toString());
            } else {
                zdryEntity.setTx(kafkaTxUrl + "/" + keyPerson.get("tx").toString());
            }
            Producer.sendMessage(servers, "keyperson", JSON.toJSONString(zdryEntity));
        }
        return true;
    }

    @Override
    public IPage<LfZdryBaseEntity> queryZdryListClear(Integer start, Integer size, String keyWords) {
        Page<LfZdryBaseEntity> page = new Page<>(start, size);
        IPage<LfZdryBaseEntity> pageResult = this.getBaseMapper().queryZdryListClear(page, keyWords);
        return pageResult;
    }

    @Override
    public Object querySsxq(ServerWebExchange exchange) {
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        List<OrganizationDto> organizationDtos = cacheableService.getUpOrgById(bo.getOrganizationBo().getId());
		/*
		  1 情报中心 和 警种的全部分局；
		  2 分局及分局一下返回分局；
		*/
        if (bo.getRoleList().get(0).getRoleType().equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())
                || bo.getRoleList().get(0).equals(RoleType.OWNER_ORG_DATA.getType())
                || bo.getRoleList().get(0).getRoleType().equals(RoleType.OWNER_REVIEW_DATA.getType())
                || bo.getRoleList().get(0).getRoleType().equals(RoleType.ADMIN_ORG_DATA.getType())) {
            List<SysDictEntity> sysDictEntityList = iSysDictService.getByType("kp_zrgkfj");
            return sysDictEntityList;
        } else {
            OrganizationDto org = null;
            OrganizationDto fjOrg = getOrganizationByCondition(organizationDtos, "分局");
            if (null != fjOrg) org = fjOrg;
            OrganizationDto xjOrg = getOrganizationByCondition(organizationDtos, "县局");
            if (null != xjOrg) org = xjOrg;
            OrganizationDto sjOrg = getOrganizationByCondition(organizationDtos, "市局");
            if (null != sjOrg) org = sjOrg;
            SysDictEntity sysDictEntity = iSysDictService.getEntityByKey("kp_zrgkfj", org.getId());
            List<SysDictEntity> list = new ArrayList<>();
            list.add(sysDictEntity);
            return list;
        }
    }

    /**
     * 每日跟踪 查询单位下拉
     * 只给市局 分局 派出所用
     *
     * @param exchange
     * @return
     */
    @Override
    public List<Map<String, Object>> findUnitByCurrentUser(ServerWebExchange exchange) {
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        List<OrganizationDto> organizationDtos = cacheableService.getUpOrgById(bo.getOrganizationBo().getId());

        List<Map<String, Object>> orgMap = null;
        if (bo.getRoleList().get(0).getRoleType().equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 情报中心所有分局
            List<SysDictEntity> sysDictEntityList = iSysDictService.getByType("kp_zrgkfj");
            orgMap = new ArrayList<>();
            for (SysDictEntity e : sysDictEntityList) {
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put("id", e.getKey());
                tempMap.put("shortName", e.getValue());
                tempMap.put("regionId", e.getKey());
                orgMap.add(tempMap);
            }
            return orgMap;
        } else if (bo.getRoleList().get(0).getRoleType().equals(RoleType.BREACH_DATA.getType())
                || bo.getRoleList().get(0).getRoleType().equals(RoleType.BREACH_REVIEW_DATA.getType())) { //分局

            OrganizationDto org = null;
            OrganizationDto fjOrg = getOrganizationByCondition(organizationDtos, "分局");
            if (null != fjOrg) org = fjOrg;
            OrganizationDto xjOrg = getOrganizationByCondition(organizationDtos, "县局");
            if (null != xjOrg) org = xjOrg;
            OrganizationDto sjOrg = getOrganizationByCondition(organizationDtos, "市局");
            if (null != sjOrg) org = sjOrg;

            orgMap = this.getBaseMapper().queryLowerlevelUnit(org.getId(), "派出所");
        } else if (bo.getRoleList().get(0).getRoleType().equals(RoleType.POLICE_STATION_DATA.getType())) { //派出所
            OrganizationDto sspcs = getOrganizationByCondition(organizationDtos, "派出所");
            //orgMap = this.getBaseMapper().queryLowerlevelUnit(sspcs.getId(),null);
            orgMap = new ArrayList<>();
            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("id", sspcs.getId());
            tempMap.put("shortName", sspcs.getShortName());
            tempMap.put("regionId", sspcs.getRegionId());
            orgMap.add(tempMap);

        }
        return orgMap;
    }

    public void operatLog(String id, ServerWebExchange exchange, LfZdryBaseEntity entity) {
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        if (bo == null) {
            throw new BusinessException(10019, "此账号已在别处登录，请查证");
        }
        StringBuffer nameIdCardStringBuffer = new StringBuffer();
        nameIdCardStringBuffer.append("删除重点人员");
        if (null != entity) {
            nameIdCardStringBuffer.append("，姓名:" + entity.getXm() + "，身份证号:" + entity.getSfzh());
        }
        //历史记录
        LfZdryHistoryLogEntity history = new LfZdryHistoryLogEntity();
        history.setCreator(bo.getPersonBo().getName());
        history.setCreatorCode(bo.getPersonBo().getPoliceCode());
        history.setCreateTime(new Date());
        history.setSpId(id);
        history.setApproveResult(nameIdCardStringBuffer.toString());
        history.setOperation("删除");
        history.setOperateDept(bo.getOrganizationBo().getShortName());
        history.setFunctionModule("重点人员模块");

        ServerHttpRequest request = exchange.getRequest();
        String ip = getRemoteIpUtil.getRemoteIP(request);
        history.setOperateIp(ip);
        //变更
        history.setType(3);
        lfZdryHistoryLogService.save(history);
    }

}


